package com.example.redis6.controller;

import com.example.redis6.model.VideoCardDo;
import com.example.redis6.service.VideoCardService;
import com.example.redis6.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description: VideoController <br>
 * date: 2021/7/20 09:07 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/api/v1/videoCard")
public class VideoCardController {

    @Autowired
    private VideoCardService videoCardService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String VIDEO_CACHE_KEY = "video:card:key";

    /**
     * 有缓存
     * @return
     */
    @GetMapping("list_cache")
    public JsonData listCard(){
        // 先读缓存
        Object cacheObj = redisTemplate.opsForValue().get(VIDEO_CACHE_KEY);

        List<VideoCardDo> videoCardList = new ArrayList<>();

        if (cacheObj != null) {
            videoCardList = (List<VideoCardDo>) cacheObj;
        }else {
            videoCardList = videoCardService.getVideoCardList();
            redisTemplate.opsForValue().set(VIDEO_CACHE_KEY,videoCardList,10, TimeUnit.MINUTES);
        }

        return JsonData.buildSuccess(videoCardList);

    }

    /**
     * 无缓存
     * @return
     */
    @GetMapping("list_nocache")
    public JsonData listCardNocache(){
        List<VideoCardDo> videoCardList = videoCardService.getVideoCardList();
        return JsonData.buildSuccess(videoCardList);
    }

}
